package com.example.booksdeal.basic;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.booksdeal.BmobDBO.User;
import com.example.booksdeal.R;
import com.example.booksdeal.util.DBOpenHelper;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import pl.com.salsoft.sqlitestudioremote.SQLiteStudioService;

public class LoginActivity extends AppCompatActivity {

    private long exitTime = 0;
    private DBOpenHelper dbOpenHelper;  //声明DBOpenHelper对象
    private EditText mName,mPwd;
    private Button mLogin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (Build.VERSION.SDK_INT >= 21){
//            View decorView = getWindow().getDecorView();
//            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        }

        setContentView(R.layout.activity_login);

        //   android点击Home键后，再打开应用，使应用恢复到原来状态，而不是重新启动
        if (!isTaskRoot()) {
            finish();
            return;
        }

        SQLiteStudioService.instance().start(this);
        dbOpenHelper = new DBOpenHelper(LoginActivity.this,"db_booksdeal.db",null,1);  //实例化DBOpenHelper对象，用来创建数据库
        mName = findViewById(R.id.name);
        mPwd = findViewById(R.id.pwd);
        mLogin = findViewById(R.id.login);
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String um = mName.getText().toString(); //获取用户账号
                String pwd = mPwd.getText().toString(); //获取用户密码
                if (um.equals("") || pwd.equals("")) {     //如果填写的账号或密码为空时
                    Toast.makeText(LoginActivity.this,"账号或密码不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    login(um,pwd);
//                    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
//                    Cursor cursor = db.query("UserInfo", null, "username=? and password=?", new String[]{um, pwd}, null, null, null);
//                    if (cursor != null && cursor.getCount() >= 1) {
//                            login(um);
//                            cursor.close();
//                    } else {
//                        Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_LONG).show();
//                    }
                }
            }
        });
    }

    /**
     * 登录用户（异步）
     */
    private void login(String um,String pwd){
        User userlogin=new User();
        userlogin.setUsername(um);
        userlogin.setPassword(pwd);
        userlogin.login(new SaveListener<User>() {
            @Override
            public void done(User bmobUser, BmobException e) {
                if(e==null){
                    // 点击按钮 代表登录成功

                    Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                    intent.putExtra("username",um);
                    startActivity(intent);

                    finish();
                    Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(LoginActivity.this,"账号或密码错误！",Toast.LENGTH_SHORT).show();
                    Log.e("登录失败", "原因: ", e);
                }
            }
        });
//        EMClient.getInstance().login(mName.getText().toString().trim(),
//                mPwd.getText().toString().trim(), new EMCallBack() {
//                    @Override
//                    public void onSuccess() {
//
//                        //保证进入主页面后本地会话和群组都 load 完毕
//                        EMClient.getInstance().groupManager().loadAllGroups();
//                        EMClient.getInstance().chatManager().loadAllConversations();
//
//                        Intent intent = new Intent();
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);  // 禁止返回
//                        intent.setClass(LoginActivity.this, MainActivity.class);
//                        Bundle bundle = new Bundle();
//                        bundle.putString("username",um);
//                        intent.putExtras(bundle);
//                        startActivity(intent);
//                        Log.i("TAG", "onSuccess: 登录成功");
//                    }
//
//                    @Override
//                    public void onError(int code, String error) {
//
//                        Log.i("TAG", "onError: 登录失败，" + error);
//                    }
//
//                    @Override
//                    public void onProgress(int progress, String status) {
//
//                    }
//                });
    }


    //注册
    public void signup(View view) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);  // 禁止返回
        intent.setClass(LoginActivity.this,RegisterActivity.class);
        startActivity(intent);
    }

    // 实现再按一次返回键退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//    protected void onDestroy() {
//        super.onDestroy();
//        if (dbOpenHelper!=null){
//            dbOpenHelper.close();  //关闭数据库连接
//        }
//    }
}
